package com.mutouren.modules.organize.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.mutouren.common.entity.ValidState;
import com.mutouren.common.utils.StringUtils;
import com.mutouren.modules.organize.dao.DepartmentDao;
import com.mutouren.modules.organize.dao.OrgDaoManager;
import com.mutouren.modules.organize.model.Department;
import com.mutouren.modules.organize.service.DepartmentService;

public class DepartmentServiceImpl implements DepartmentService {

	private static DepartmentDao departmentDao;

	static {
		departmentDao = OrgDaoManager.getOrgDaoFactory().getDepartmentDao();
	}
	
	public DepartmentServiceImpl() {
		System.out.println("----------create DepartmentServiceImpl");
	}

	@Override
	public Department get(int id) {
		if(Department.ROOT_ID.equals(id)) {
			return Department.createRootDepartment();
		} else {
			Department dpt = departmentDao.get(id);
			if((dpt != null)&&(dpt.getParentDepartment().getId() == Department.ROOT_ID)) {
				dpt.setParentDepartment(Department.createRootDepartment());
			}
			return dpt;
		}
	}

	@Override
	public void save(Department department) {			
		departmentDao.save(department);
	}

	@Override
	public int update(Department department) {
		return departmentDao.update(department);
	}

	@Override
	public int setValidState(int id, ValidState validState) {
		return departmentDao.SetValidState(id, validState.value);
	}

	@Override
	public List<Department> findChildren(Department department, boolean isCascade) {
		if (isCascade) {
			return departmentDao.findChildByParentIdPath(department.buildSelfIdPath(), true);
		} else {
			return departmentDao.findChildByParentId(department.getId());
		}
	}

	@Override
	public List<Department> findParents(Department department, boolean isContainSelf) {
		List<Department> result;
		
		if (department.isRoot() || department.getParentIdPath().equals(String.format("%s,", Department.ROOT_ID))) {
			result = new ArrayList<Department>();
		} else {
			result = departmentDao.findByListId(StringUtils.toListInteger(department.getParentIdPath(), ","));
		}
		
		if(isContainSelf) {
			result.add(department);			
		}
		
		if(!department.isRoot()) {			
			result.add(0, Department.createRootDepartment());
		}
			
		return result;
	}

}
